DATE=`TZ=$TZ date '+%Y%d%m'`
pid=$$
ppid=$(ps -o ppid= -p $pid)
parent_cmd=$(ps -o cmd= $ppid)
RUNTIMEMAINDIR_LOCAL=$(dirname $(readlink -f $0))
log_file_name="$DATE_exec_sql.log"
RUNTIMEMAINDIR_LOCAL=$(echo $(echo ${RUNTIMEMAINDIR_LOCAL%_entegor*})"_entegor/batchshell/tmplog/sqllog")
[ ! -d "$RUNTIMEMAINDIR_LOCAL" ] && mkdir -p "$RUNTIMEMAINDIR_LOCAL"
log_file="${RUNTIMEMAINDIR_LOCAL}/${log_file_name}"

function sql_exec(){
    userid=$1
    block=$2
    mode=$3
    if [ $mode -eq 0 ]; then
        gsql $userid <<EOF
        \a
        \f =
        \x on
            $block
        \q
EOF
        echo sql_conn_stat="$?"
    else
        gsql $userid <<EOF
            \a
            \f =
                $block
            \q
EOF
        echo sql_conn_stat="$?"
    fi
}

function deal_res(){
    res="$1"

    #连接状态
    sql_conn_stat="$(echo "$res" | awk -F= '/^sql_conn_stat/ { print $2}')"
    #编译状态
    error_cnt="$(echo "$res" | grep -i 'ERROR:' | wc -l)"
    if [[ $sql_conn_stat -eq 0 && $error_cnt -eq 0 ]]; then
        #连接成功
        echo retCode=0
    else
        echo retCode=1
    fi

    #简化输出，删除无用的输出
    res="$(echo "$res" \
        | grep -v 'Output format is unaligned.' \
        | grep -v 'Field separator is "=".' \
        | grep -v 'Expanded display is on.' \
        | grep -v 'ANONYMOUS BLOCK EXECUTE' \
        | grep -v 'sql_conn_stat')"

    #返回结果
    echo "$res"
}

userid_without_pwd=$(echo "$1" | sed 's/\(.*\) -W.*/\1/')
{
    echo "$(date +%Y-%m-%d_%H:%M:%S) | PID: $pid | start running")
    echo "$(date +%Y-%m-%d_%H:%M:%S) | PID: $pid | parent_shell_name: $parent_cmd"
    echo "$(date +%Y-%m-%d_%H:%M:%S) | PID: $pid | userid: ${userid_without_pwd}"
    echo "$(date +%Y-%m-%d_%H:%M:%S) | PID: $pid | block: $2"
    echo "$(date +%Y-%m-%d_%H:%M:%S) | PID: $pid | mode: $3"
    echo "$(date +%Y-%m-%d_%H:%M:%S) | PID: $pid | exec_sql_info:"
    res=$(sql_exec "$1" "$2" "$3" 2>&1 | grep -v -E 'Output format is unaligned.|Field separator is "=".|ANONYMOUS BLOCK EXECUTE|Expanded display is on.' | tee -a "$log_file")
    echo "$(date +%Y-%m-%d_%H:%M:%S) | PID: $pid | deal_sql_info:"
    res=$(deal_res "$res" | tee -a "$log_file")
    echo "$(date +%Y-%m-%d_%H:%M:%S) | PID: $pid | end run"
} >> "$log_file"
echo "$res"